﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Application;
using Casamiel.Common;
using Enyim.Caching;
using MediatR;
using Microsoft.Extensions.Options;

namespace Casamiel.API.Application.Commands
{
    /// <summary>
    /// Create wx extension command handler.
    /// </summary>
    public class CreateWxExtensionCommandHandler : IRequestHandler<CreateWxExtensionCommand, bool>
    {
        private readonly IWxExtensionService _wxExtensionService;
        private readonly IMemberCardService _cardService;
        private readonly IMemcachedClient _memcachedClient;
        private readonly string _memcachedPrex;
        

        /// <summary>
        /// Initializes a new instance of the
        /// </summary>
        /// <param name="wxExtension">Wx extension.</param>
        /// <param name="cardService">Card service.</param>
        ///<param name="memcachedClient"></param>
        ///<param name="options"></param>
        public CreateWxExtensionCommandHandler(IWxExtensionService wxExtension, IMemberCardService cardService,IMemcachedClient memcachedClient,IOptionsSnapshot<CasamielSettings>  options )
        {
            _wxExtensionService = wxExtension;
            _cardService = cardService;
            _memcachedClient = memcachedClient;
            _memcachedPrex = options.Value.MemcachedPre;
        }
        /// <summary>
        /// Handle the specified request and cancellationToken.
        /// </summary>
        /// <returns>The handle.</returns>
        /// <param name="request">Request.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<bool> Handle(CreateWxExtensionCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            var mobile = request.WxInfo.Mobile;
            if (!string.IsNullOrEmpty(mobile))
            {
                var card = await _cardService.GetBindCardAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
                if (card != null)
                {
                    return false;
                }
            }

            var _cachekey = _memcachedPrex + Constant.WxExtension + request.WxInfo.Id;


            var trynum = _memcachedClient.Increment(_cachekey, 1, 1);
            if (trynum == 1) {
                var entity = await _wxExtensionService.FindAsync<ICasaMielSession>(request.WxInfo.Id).ConfigureAwait(false);
                if (entity == null) {
                    entity = new Domain.Entity.WxExtension {
                        WxId = request.WxInfo.Id,
                        OpenId = request.WxInfo.OpenId,
                        Mobile = request.WxInfo.Mobile,
                        Status = 0,
                        ShopId = request.ShopId,
                        CreateTime = DateTime.Now
                    };


                    await _wxExtensionService.AddAsync<ICasaMielSession>(entity).ConfigureAwait(false);
                    
                } else if (entity.Status == 0) {
                    entity.ShopId = request.ShopId;
                    entity.UpdateTime = DateTime.Now;
                    entity.Mobile = request.WxInfo.Mobile;
                    await _wxExtensionService.UpdateAsync<ICasaMielSession>(entity).ConfigureAwait(false);
                }
                
            }
            

            return true;
        }
    }
}
